<!--企业安全环保基本信息表 sanction-->
<template>
    <Layout>
        <Form ref="queryForm" :model="dataToQuery" :label-width="120">
            <Row class="query-form" >
                <Col span="8">
                  <FormItem label="二级集团：" prop="order">
                    <two-level-org org-code v-model="dataToQuery.twoLevelGroupId" ></two-level-org>
                  </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label='企业名称：'>
                      <company-select v-model="dataToQuery.companyName"></company-select>
                    </FormItem>
                </Col>
                <Col span="8" v-if="!switchFlag">
                 <!--   <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>-->
                    <Button @click="reseter" class="ivu-btn-reset"  >重置</Button>
                    <Button type="primary" class="ivu-btn-query"   icon="md-search"  @click="query">查询</Button>
                </Col>
                <Col span="8" v-else>

                </Col>
            </Row>
            <Row  v-show="switchFlag" class="query-form" >

                <Col span="8" :offset="16">
                    <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
                    <Button @click="reseter" class="ivu-btn-reset">重置</Button>
                    <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                </Col>
            </Row>
            <Row class="query-form">
                <Col span="24">
                    <Button size="large"  class="ivu-btn-add" icon="md-add"  @click="addInfo">新增</Button>
                   <Button type="primary" class="ivu-btn-add"   icon="md-cloud-download"  @click="exportFormSubmit" :loading="exportLoading">导出</Button>
                </Col>
            </Row>
        </Form>
        <Table ref='table' :height="tableHeight"  no-data-text="没有查询到相关数据!" @on-selection-change = 'getSelectRows' :loading='pageStatus.loading ||  pageStatus.baseLoading' @on-sort-change="querySort"
               border :columns="columns1"  :data="dataTable" show-summary :summary-method="handleSummary">
        </Table>
        <Row style="margin-right:10px;">
            <Col span="24" >
                <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange1" @on-page-size-change="pageSizeChange1" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
            </Col>
        </Row>
        <Modal  :title="mode == 'view' ?'安全行政处罚表详情':'安全行政处罚表'" :transfer=false :mask-closable="false" v-model="dialogShow" v-if="dataToView && dialogShow" :width=800 :styles="{height:'559px'}"  class-name='limit-height-dialog'>
            <Row>
                <Col span="24">
                    <Form ref="dataToView" :class="mode === 'view'?'modal-view-detail':'modal-form'" :show-message="false" :model="dataToView" :rules="mode === 'view'?{} :ruleCustom"  :label-position="mode === 'view'?'right':'top'" :label-width="mode === 'view'?160:null">
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label='所属集团：' >
                                    <div v-if="mode === 'view'">{{ dataToView.twoLevelGroupName }}</div>
                                    <Input v-else class='' type='text' v-model='dataToView.twoLevelGroupName' :readonly="true"></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='被罚款单位：' prop='companyName'>
                                    <div v-if="mode === 'view'">{{ dataToView.companyName }}</div>
                                    <!--    <Input v-else class=''placeholder="请选择企业名称" type='text' v-model='dataToView.companyName' :readonly="true" @on-focus="openSelect"></Input>-->
                                    <cascaderDom v-else  class="query-form-el" ref="groupOrg"
                                                 @setOrgInfo='(data)=>{cascaderDomIdChangeHandle(data,"companyId");}'
                                                 @setOrgname='(data)=>{cascaderDomNameChangeHandle(data,"companyName");}'
                                                 :currentOrgId = "dataToView.companyId"
                                                 :setCurrentName="{label:dataToView.companyName, value:dataToView.companyId}"
                                                 :orgTree="true" ></cascaderDom>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='罚款单位：' prop='fineUnitName'>
                                    <div v-if="mode === 'view'">{{ dataToView.fineUnitName }}</div>
                                    <Input v-else class='' placeholder="请填写罚款单位" type='text' v-model='dataToView.fineUnitName'></Input>
                                </FormItem>
                            </Col>

                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">

                            <Col span="11">
                                <FormItem label='罚款时间：' prop='fineDate'>
                                    <div v-if="mode === 'view'">{{ renderViewDate(dataToView.fineDate) }}</div>
                                    <DatePicker v-else class="w" placeholder="请选择罚款时间" v-model='dataToView.fineDate' ></DatePicker>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='罚款金额(万元)：' prop='fineMoney'>
                                    <div v-if="mode === 'view'">{{ dataToView.fineMoney }}</div>
                                    <InputNumber v-else class='w'placeholder="请填写罚款金额" min="0" type='text' v-model='dataToView.fineMoney'></InputNumber>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">

                            <Col span="23">
                                <FormItem label='罚款事由：' prop='reasonsForFines'>
                                    <div v-if="mode === 'view'">{{ dataToView.reasonsForFines }}</div>
                                    <Input v-else class=''placeholder="请填写罚款事由" type='text' v-model='dataToView.reasonsForFines'></Input>
                                </FormItem>
                            </Col>

                        </Row>

                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label='罚款内容描述：' prop='fineDesc'>
                                    <div v-if="mode === 'view'">{{ dataToView.fineDesc }}</div>
                                    <Input v-else class=''placeholder="请填写罚款内容描述" type='textarea' v-model='dataToView.fineDesc'></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem v-if="mode === 'view'" label="罚款单、罚款说明等文件或图片：">
                                    <div v-show="dataToView.idFiles.length>0" v-for="item in dataToView.idFiles">
                                        <a @click="downloadFile(item)"><span style="color: #3399ff;margin-left: 5px">{{ item.fileName }}</span></a>
                                    </div>
                                </FormItem>
                                <FormItem v-else label="上传附件(罚款单、罚款说明等文件或图片)：" prop="idFiles">
                                    <div >
                                        <Upload ref="upload"
                                                :before-upload="(file) => { beforeUpload(file, 'id') }"
                                                :show-upload-list="true"
                                                :max-size="10240"
                                                multiple
                                                type="drag"
                                                :action="fileUrl">
                                            <div style="padding: 20px">
                                                <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                                                <p>点击将文件拖拽到这里上传</p>
                                            </div>
                                        </Upload>
                                    </div>
                                    <div v-show="dataToView.idFiles.length>0" v-for="item in dataToView.idFiles">
                                        <a @click.prevent="downloadFile(item)">{{item.fileName}}</a>
                                        <Button type="text" icon="md-trash" @click="removeFile(item.id, 'id')"
                                                style="margin-left: 20px;margin-bottom: 3px"/>
                                    </div>
                                </FormItem>
                            </Col>
                        </Row>
						<Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='安全总监或安全工作主管：' prop='approvalUser'>
                                    <div v-if="mode === 'view'">{{dataToView.approvalUserName}}</div>
                                    <div v-else>
                                        <userDom class='query-form-el' ref="userDom" :selectData='setCurrentUserName'
                                                 :placeholderStr="'请选择安全总监或安全工作主管'"
                                         :singleChoice=true :ifUser="true" :rootOrgName="dataToView.companyName"
                                         @setData = '(data)=>{ if(data){this.$set(dataToView, "approvalUser", data.userId),this.$set(dataToView, "approvalUserName", data.userName)}}'></userDom>
                                    </div>
                                </FormItem>
                            </Col>
							<Col span="11">
                                <FormItem label='创建人：' prop='registrant'>
                                <div v-if="mode === 'view'">{{dataToView.userName}}</div>
                                <Input v-else type='text' v-model='dataToView.userName' readonly></Input>
                            </FormItem>
							</Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
							<Col span="11">
							<FormItem label='创建时间：' prop='registTime'>
								<div v-if="mode === 'view'">{{renderViewDate(dataToView.createDate)}}</div>
								<DatePicker v-else type="date" placeholder="请选择日期" class="w" v-model='dataToView.createDate' readonly></DatePicker>
							</FormItem>
							</Col>
							<Col span="11">
							<FormItem label='创建人电话：' prop='createMobile'>
								<div v-if="mode === 'view'">{{dataToView.createMobile}}</div>
								<Input v-else type='text' v-model='dataToView.createMobile'></Input>
							</FormItem>
							</Col>
						</Row>
                    </Form>
                </Col>
            </Row>
            <div slot="footer">
                <Button v-if="mode != 'view'" type="primary"  class='ivu-btn-save' @click="submit('dataToView')" >确定</Button>
                <Button v-if="mode != 'view'" type="primary"  class='ivu-btn-cancel' @click="handleCancel" >取消</Button>
                <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
            </div>
        </Modal>


        <Modal :transfer=false v-model="model4"  :width=900>
            <Tabs>
                <TabPane label="历史记录">
                    <Table ref='table1' border :columns="columns2" no-data-text="没有查询到相关数据！" style="margin-top: 0" :loading="loading2"
                           :data="history" width="100%"  :height="450" highlight-row stripe size="small"></Table>
                </TabPane>
                <TabPane label="流程图">
                    <div style="height: 450px; overflow-y: auto; overflow-x: auto">
                        <img :src="imgUrl" >
                    </div>
                </TabPane>
            </Tabs>
            <div slot="footer">
                <Button @click="model4=false" class="ivu-btn-save">关闭</Button>
            </div>
        </Modal>
    </Layout>
</template>

<script>
    import {Api} from '@/api/index.js'
    import {sessionStorage} from '@/common/cacheUtils.js';
    import {formatDate} from '@/tools/index'
    import userDom from "@/components/input-user.vue";
    var cascaderDom = () => import('@/components/cascader-dom.vue');
    import pageCommonFunction from '@/components/pageCommonFunction.js'
    export default {
        components:{cascaderDom, userDom},
        computed:{

        },
        data(){
            return {
                ...this.createCommonDataField(),
                switchFlag:false,
                columns1: [
                    { key:'key', title: '序号', width: 80, fixed: 'left', align: 'center', render: this.indexColumnsRenderSum},
                    {key: 'approval', title: '审批状态', align: 'center',fixed: 'left', minWidth: 90, render: (h, params) => {
                        if(params.row.id != '-1'){
                          return h('span', {style: {color: params.row.procinstState=='1'?'blue':params.row.procinstState=='2'?'red':params.row.procinstState=='3'?'green':'red'}},
                              params.row.procinstState=='1'?'待审批':params.row.procinstState=='2'?'审批退回':params.row.procinstState=='3'?'审批通过':params.row.procinstState=='5'?'流程终止':'待提交')
                        }else{
                          return h('span', '');
                        }
                    }},
                    { key:'companyName',fixed: 'left',title: '被罚款单位',  minWidth: 150, align: 'center' },
                    { key:'fineUnitName',fixed: 'left',title: '罚款单位', minWidth: 150,   align: 'center' },
                    { key:'fineDate',title: '罚款时间',  align: 'center',  minWidth: 110, render: this.renderCellDate, sortable: 'custom'},
                    { key:'fineMoney',title: '罚款金额(万元)',  align: 'center', minWidth: 100,  },
                    { key:'reasonsForFines',title: '罚款事由',  align: 'center', minWidth: 150, tooltip:true },
                    { key:'fineDesc',title: '罚款内容描述',  align: 'center', minWidth: 150,  tooltip:true},
                    { key:'approvalUserName',title: '安全总监或安全工作主管',  minWidth: 100,  align: 'center',},
                    { key:'twoLevelGroupName',title: '所属集团',   minWidth: 150, align: 'center' },
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        width: 270,
                        align: 'center',
                        render: (h, params) => {
                            if(params.row.id == -1){
                              return;
                            }
                            const enable = this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId ||this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined || this.currentUser.userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined;
                            return h('div', [
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {fontSize: '14px',},
                                    on: {
                                        click: () => {
                                            this.viewData(params);
                                        }
                                    }
                                }, '详情'),
                                h('Divider', { props: { type: 'vertical' } }, ''),
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {fontSize: '14px',
                                        color: (params.row.procinstId == null||params.row.procinstState=='5')&&enable?'':'#c5c8ce',
                                        pointerEvents:(params.row.procinstId == null||params.row.procinstState=='5')&&enable?'':'none'},
                                    on: {
                                        click: () => {
                                            if((params.row.procinstId == null||params.row.procinstState=='5')&&enable) {
                                                this.editData(params);
                                            }
                                        }
                                    }
                                }, '修改'),
                                h('Divider', { props: { type: 'vertical' } }, ''),
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {fontSize: '14px',
                                        color: (params.row.procinstState==0||params.row.procinstState=='5')&&enable?'red':'#c5c8ce',
                                        pointerEvents:(params.row.procinstState==0||params.row.procinstState=='5')&&enable?'':'none'},
                                    on: {
                                        click: () => {
                                            if((params.row.procinstState==0||params.row.procinstState=='5')&&enable) {
                                                this.deleteData(params);
                                            }
                                        }
                                    }
                                }, '删除'),
                                h('Divider', { props: { type: 'vertical' } }, ''),
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {fontSize: '14px',
                                        color: params.row.approvalUser&&(params.row.procinstState==0||params.row.procinstState=='5')&&enable?'':'#c5c8ce',
                                        pointerEvents:params.row.approvalUser&&(params.row.procinstState==0||params.row.procinstState=='5')&&enable?'':'none'},
                                    on: {
                                        click: () => {
                                            if((params.row.procinstState==0||params.row.procinstState=='5')&&enable) {
                                                this.subView(params.row);
                                            }
                                        }
                                    }
                                }, '上报'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('a', {
                                    props: {
                                        type: 'primary',
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: params.row.procinstId == null ? '#d0d0d0' : '',
                                        pointerEvents: params.row.procinstId == null ? 'none' : ''
                                    },
                                    on: {
                                        click: () => {
                                            this.imgUrl = Api.getFlowImg + '/' + params.row.procinstId
                                            this.showHistory(params.row);
                                        }
                                    }
                                },'流程图')
                            ]);
                        }
                    },
                ],
                ruleCustom : {
                    approvalUser: [ { required: true, message: '请选择安全总监或安全工作主管', trigger: 'change',}],
                    companyName: [ { required: true, message: '请填写企业名称', trigger: 'change',}],
                    twoLevelGroupName: [ { required: true, message: '请填写所属集团', trigger: 'change',}],
                    reasonsForFines: [ { required: true, message: '请填写罚款事由', trigger: 'change',}],
                    fineUnitName: [ { required: true, message: '请填写罚款单位', trigger: 'change',}],
                    fineDate: [ { required: true, message: '请填写罚款时间', trigger: 'change',type:'date'}],
                    fineMoney: [ { required: true, trigger: 'change',message:'请填写0-9数字包括小数',
                        validator: (rule, value, callback) => {
                            if (!(/^(([^0][0-9]+|0)\.([0-9]{1,8})$)|^(([^0][0-9]+|0)$)|^(([1-9]+)\.([0-9]{1,8})$)|^(([1-9]+)$)/.test(value))) {
                                callback(' ');
                            } else {
                                callback()
                            }
                        },
                    }],
                  idFiles: [ { required: true, trigger: 'change',message:'请上传附件',
                        validator: (rule, value, callback) => {
                            if (this.dataToView.idFiles == undefined || this.dataToView.idFiles == null || this.dataToView.idFiles.length == 0) {
                                callback('请上传附件');
                            } else {
                                callback()
                            }
                        },
                    }],
                    fineDesc: [ { required: true, message: '请填写罚款内容描述', trigger: 'change',}],
					createMobile: [{pattern: /^((0\d{2,3}-\d{7,8})|(1[3675849]\d{9}))$/,required: true,message: '请填写填报人电话',trigger: 'change'}],
                },
                tableHeight:10,
                // api
                queryUrl:Api.SaAdministrativeSanctionQuery,
                deleteUrl:Api.SaAdministrativeSanctionDelete,
                updateUrl:Api.SaAdministrativeSanctionUpdate,
                saveUrl:Api.SaAdministrativeSanctionSave,
				exportUrl:Api.SaAdministrativeSanctionExport,
                setCurrentUserName:{},

                history:[],
                model4:false,
                loading2:false,
                imgUrl:"",
                columns2: [
                    {
                        type: 'index',
                        title: '序号',
                        width: 80,
                        align: 'center',
                    },
                    {
                        width: 180,
                        title: '审批时间',
                        key: 'endTime',
                        align: 'center',
                    },
                    {
                        width: 185,
                        title: '节点名称',
                        key: 'name',
                        align: 'center',
                    },
                    {
                        width: 120,
                        title: '审批人',
                        key: 'userName',
                        align: 'center'
                    },
                    {
                        width: 100,
                        title: '审批意见',
                        key: 'route',
                        align: 'center'
                    },
                    {
                        width: 200,
                        title: '备注',
                        key: 'opinions',
                        align: 'center'
                    },
                ],
            }
        },
        async mounted() {
            this.dataToQuery ={};
            this.setSumTableHeight();
            this.query();
        },
        methods:{

            ...pageCommonFunction,
            deleteData(params) {
                this.deleteDateById(params.row.id);
            },
            switchQuery(flag) {
                this.switchFlag = flag;
                if (!this.switchFlag) {
                    this.tableHeight = this.tableHeight + 44;

                } else {
                    this.tableHeight = this.tableHeight - 44;
                }

            },
            setOrgId(data) {
                this.dataToQuery.companyId = data[data.length - 1];
            },
            setOrgName(data) {

            },
            query() {
                this.pagedata.currentPage = 1;
                this.query1()
            },
            submit(name) {
                this.submitBase(name);
            },
            createEmptyDataToAdd() {
                return{
                    id:this.get_uuid(),
                    idFiles:[],
                    companyId:sessionStorage('userId').getObject('userId').companyId,
                    companyName:sessionStorage('userId').getObject('userId').companyName,
                    twoLevelGroupId:sessionStorage('userId').getObject('userId').twoLevelOrgId,
                    twoLevelGroupName:sessionStorage('userId').getObject('userId').twoLevelOrgName,
					createMobile: sessionStorage('userId').getObject('userId').mobileNumber,
					userName: sessionStorage('userId').getObject('userId').userName,
                    fineMoney:0
                }
            },
            reseter() {
                this.dataToQuery = {};
                // this.$refs.groupOrg1.resetCurrentOrg();
                this.query()
            },
			exportFormSubmit() {
				this.buttonLoading = true
				let orgId = sessionStorage('userId').getObject('userId').companyId
				let data = {
					orgId: orgId,
				};
				data = Object.assign(data, JSON.parse(JSON.stringify(this.dataToQuery)));
				this.$http.get(Api.SaAdministrativeSanctionExport, {
					params: data,
					responseType: 'blob' //告诉服务器我们需要的响应格式
				}).then((res) => {
					const aLink = document.createElement("a");
					let blob = new Blob([res.data], {
						type: res.bodyBlob.type //将会被放入到blob中的数组内容的MIME类型
					});
					aLink.href = URL.createObjectURL(blob)
					aLink.download = "安全行政处罚表(" + formatDate(new Date(), "yyyy-MM-dd") + ").xlsx" //标题
					aLink.click()
					document.body.appendChild(aLink)
					this.buttonLoading = false
				})
			},
            async editData(data) {
                this.setCurrentUserName = {name:data.row.approvalUserName}
                //修改页面
                this.mode = 'edit'
                this.dataToView = {...data.row}
                await this.afterDataToViewInit()

                this.dialogShow = true;
                setTimeout(()=>{
                    this.dialogVisibleChangeHandele(this.dialogShow)
                    this.$refs.userDom.setCurrentInfo();
                },100)
            },
            async afterDataToViewInit() {
                await this.getFiles('id');
            },

            subView(row){
                this.$Modal.confirm({
                    title: '提示',
                    content: '<p>是否要提交？</p>',
                    onOk: () => {
                        let map ={
                            workId: row.id,
                            createUserId: sessionStorage('userId').getObject('userId').userId,
                            userName: sessionStorage('userId').getObject('userId').userName,
                            key: 'sanction',
                            formKey: 'sanctionApproval',
                            user1: row.approvalUser,
                        }
                        this.$http.post(Api.submit, map).then(function(res){
                            // this.sendMessage(row.approvalUser);
                            this.buttonLoading = false;
                            this.modal4 = false;
                            if(res.data.status == 200){
                                this.$Message.success({ content: '上报成功', duration: 4 });
                                this.query();
                            }else{
                                this.$Message.error({ content: res.data.msg, duration: 4 });
                            }
                        });
                    },
                });
            },
            showHistory(row) {
                this.model4 = true;
                this.loading2 = true;
                this.$http.get(Api.getHistory + '/' + row.procinstId, {params: {}}).then((res) => {
                    this.history = res.data;
                    this.loading2 = false;
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },
            querySort({column, key, order}){
              this.pagedata.currentPage = 1;
              this.dataToQuery.order = order;
              this.dataToQuery.key = key;
              this.query1()
            },
            handleSummary({ columns, data }){
              let temp = JSON.parse(JSON.stringify(data));
              temp.splice(0, 1);
              const sums = {};
              columns.forEach((column, index) => {
                const key = column.key;
                if (index === 0) {
                  sums[key] = {
                    key,
                    value: '合计'
                  };
                  return;
                }
                const values = temp.map(item => Number(item[key]));
                if (!values.every(value => isNaN(value))) {
                  const v = values.reduce((prev, curr) => {
                    const value = Number(curr);
                    if (!isNaN(value)) {
                      return prev + curr;
                    } else {
                      return prev;
                    }
                  }, 0);
                  sums[key] = {
                    key,
                    value: v
                  };
                } else {
                  sums[key] = {
                    key,
                    value: ''
                  };
                }
              })
              return sums;
            }
        },
        watch:{

        },

    }
</script>

<style lang='css' scoped>
    @import '../../../index.css';
</style>
